import lib.db as database
import lib.XLSX as xlsx


def Update_Vis_db(Vissim, step, Road_name):
    db = database.database()
    bus_id = []
    add_mess = []

    try:
        vehicles_list = Vissim.Net.Vehicles  # to get all vehicles obj in the current vissim net
        for vehicle in vehicles_list:
            # select the bus obj from all the vehicles
            if vehicle.AttValue("TYPE") == 300:
                bus_id.append(vehicle.ID)  # get the bus id

        # get each of the bus's message
        for item in bus_id:
            bus = Vissim.Net.Vehicles.GetVehicleByNumber(item)
            bus_mess = {}
            bus_mess['Bus_id'] = str(item)
            bus_mess['COO_X'] = str((round(bus.AttValue("POINT").X, 2) + 9890000) / 85000)
            bus_mess['COO_Y'] = str((round(bus.AttValue("POINT").Y, 2) + 3393000) / 85000)
            bus_mess['SPEED'] = str(round(bus.AttValue("SPEED"), 2))
            bus_mess['PASSENGERS'] = str(int(bus.AttValue("PASSENGERS")))
            bus_mess['LINK'] = str(bus.AttValue("LINK"))

            if int(eval(bus_mess['SPEED'])) % 2 == 0:
                speed = int(eval(bus_mess['SPEED']))
            else:
                speed = int(eval(bus_mess['SPEED'])) - 1
            data = xlsx.Read_xlsx_a_row('./data/discharge_data.xlsx', 0, speed/2+1)

            bus_mess['CO'] = str(round(5 * float(bus_mess['SPEED']) * data[5], 2))
            bus_mess['CO2'] = str(round(5 * float(bus_mess['SPEED']) * data[6], 2))
            bus_mess['HC'] = str(round(5 * float(bus_mess['SPEED']) * data[7], 2))
            bus_mess['NOX'] = str(round(5 * float(bus_mess['SPEED']) * data[8], 2))

            item_mess = (
                bus_mess['Bus_id'], bus_mess['LINK'], bus_mess['PASSENGERS'], '0', bus_mess['SPEED'], bus_mess['COO_X'],
                bus_mess['COO_Y'])

            his_mess = (
                bus_mess['Bus_id'], str(step), Road_name[bus_mess['LINK']], bus_mess['SPEED'], bus_mess['PASSENGERS'],
                bus_mess['COO_X'], bus_mess['COO_Y'], bus_mess['CO'], bus_mess['CO2'], bus_mess['HC'], bus_mess['NOX'])
            add_mess.append(item_mess)
            db.add_His_Bus(his_mess)

        # clear all the bus data
        db.Delete_Bus()
        for item in add_mess:
            db.add_Bus(item)

    except:
        print("error")


if __name__ == '__main__':
    Update_Vis_db(Vissim=None)
